package com.example.socialapp.ui.main.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Whatshot
import androidx.compose.material.icons.outlined.Comment
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Share
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import kotlin.math.absoluteValue

/**
 * 主页Tab界面
 *
 * @param onNavigateToSettings 导航到设置界面回调
 * @param onNavigateToCreatePost 导航到创建动态界面回调
 * @param onNavigateToSearch 导航到搜索界面回调
 * @param onNavigateToPostDetail 导航到帖子详情界面回调
 * @param onNavigateToNotification 导航到通知界面回调
 * @param onNavigateToBookmark 导航到收藏界面回调
 * @param onNavigateToRecommendation 导航到推荐界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    onNavigateToSettings: () -> Unit = {},
    onNavigateToCreatePost: () -> Unit = {},
    onNavigateToSearch: () -> Unit = {},
    onNavigateToPostDetail: (String) -> Unit = {},
    onNavigateToNotification: () -> Unit = {},
    onNavigateToBookmark: () -> Unit = {},
    onNavigateToRecommendation: () -> Unit = {}
) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("首页") },
                actions = {
                    IconButton(onClick = { onNavigateToRecommendation() }) {
                        Icon(
                            imageVector = Icons.Filled.Whatshot,
                            contentDescription = "推荐"
                        )
                    }
                    IconButton(onClick = { onNavigateToBookmark() }) {
                        Icon(
                            imageVector = Icons.Default.Bookmark,
                            contentDescription = "收藏"
                        )
                    }
                    IconButton(onClick = { onNavigateToNotification() }) {
                        Icon(
                            imageVector = Icons.Default.Notifications,
                            contentDescription = "通知"
                        )
                    }
                    IconButton(onClick = { onNavigateToSearch() }) {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索"
                        )
                    }
                    IconButton(onClick = { onNavigateToSettings() }) {
                        Icon(
                            imageVector = Icons.Default.Settings,
                            contentDescription = "设置"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = onNavigateToCreatePost,
                containerColor = MaterialTheme.colorScheme.primary
            ) {
                Icon(
                    imageVector = Icons.Default.Edit,
                    contentDescription = "发布动态",
                    tint = MaterialTheme.colorScheme.onPrimary
                )
            }
        }
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            item {
                StorySection()
                Spacer(modifier = Modifier.height(8.dp))
                Divider()
            }
            
            items(samplePosts) { post ->
                PostItem(
                    post = post,
                    onPostClick = { onNavigateToPostDetail("post-${post.user.name}") }
                )
                Divider()
            }
        }
    }
}

/**
 * 故事/状态部分
 */
@Composable
private fun StorySection() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        Text(
            text = "好友动态",
            style = MaterialTheme.typography.titleMedium,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
        )
        
        LazyRow(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 16.dp)
        ) {
            items(sampleUsers) { user ->
                StoryItem(user = user)
            }
        }
    }
}

/**
 * 单个故事/状态项
 */
@Composable
private fun StoryItem(user: User) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.padding(end = 8.dp)
    ) {
        Box(
            modifier = Modifier
                .size(64.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.primaryContainer)
                .padding(2.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .clip(CircleShape)
                    .background(getColorForUser(user))
            ) {
                Text(
                    text = user.name.first().toString(),
                    style = MaterialTheme.typography.headlineSmall,
                    color = Color.White,
                    modifier = Modifier.align(Alignment.Center)
                )
            }
        }
        
        Text(
            text = user.name,
            style = MaterialTheme.typography.bodySmall,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier.padding(top = 4.dp)
        )
    }
}

/**
 * 单个帖子项
 */
@Composable
private fun PostItem(
    post: Post,
    onPostClick: () -> Unit = {}
) {
    var liked by remember { mutableStateOf(false) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
            .clickable(onClick = onPostClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
        shape = RoundedCornerShape(0.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            // 帖子头部 - 用户信息
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(getColorForUser(post.user))
                ) {
                    Text(
                        text = post.user.name.first().toString(),
                        style = MaterialTheme.typography.bodyLarge,
                        color = Color.White,
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
                
                Column(
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 8.dp)
                ) {
                    Text(
                        text = post.user.name,
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = post.timeAgo,
                        style = MaterialTheme.typography.bodySmall
                    )
                }
                
                IconButton(onClick = { /* 更多选项 */ }) {
                    Icon(
                        imageVector = Icons.Default.MoreVert,
                        contentDescription = "更多选项"
                    )
                }
            }
            
            // 帖子内容
            Text(
                text = post.content,
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(vertical = 8.dp)
            )
            
            // 帖子互动按钮
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                IconButton(onClick = { liked = !liked }) {
                    Icon(
                        imageVector = if (liked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        tint = if (liked) Color.Red else MaterialTheme.colorScheme.onSurface
                    )
                }
                
                IconButton(onClick = { /* 评论 */ }) {
                    Icon(
                        imageVector = Icons.Outlined.Comment,
                        contentDescription = "评论"
                    )
                }
                
                IconButton(onClick = { /* 分享 */ }) {
                    Icon(
                        imageVector = Icons.Outlined.Share,
                        contentDescription = "分享"
                    )
                }
            }
            
            // 帖子统计
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 4.dp),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "${post.likes + (if (liked) 1 else 0)} 赞",
                    style = MaterialTheme.typography.bodySmall
                )
                
                Text(
                    text = "${post.comments} 评论",
                    style = MaterialTheme.typography.bodySmall
                )
                
                Text(
                    text = "${post.shares} 分享",
                    style = MaterialTheme.typography.bodySmall
                )
            }
        }
    }
}

/**
 * 根据用户名生成一个固定的颜色
 */
private fun getColorForUser(user: User): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[user.name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 示例用户数据类
 */
data class User(val name: String)

/**
 * 示例帖子数据类
 */
data class Post(
    val user: User,
    val content: String,
    val timeAgo: String,
    val likes: Int,
    val comments: Int,
    val shares: Int
)

/**
 * 示例用户列表
 */
private val sampleUsers = listOf(
    User("张三"),
    User("李四"),
    User("王五"),
    User("赵六"),
    User("钱七"),
    User("孙八"),
    User("周九"),
    User("吴十")
)

/**
 * 示例帖子列表
 */
private val samplePosts = listOf(
    Post(
        user = User("张三"),
        content = "今天天气真好，出去玩了一天，感觉非常放松！分享一些美好时光给大家。希望大家周末也有愉快的体验！",
        timeAgo = "10分钟前",
        likes = 15,
        comments = 3,
        shares = 1
    ),
    Post(
        user = User("李四"),
        content = "刚刚看了一部超赞的电影，情节紧凑，演员表演到位，强烈推荐给大家！",
        timeAgo = "30分钟前",
        likes = 24,
        comments = 8,
        shares = 2
    ),
    Post(
        user = User("王五"),
        content = "学习编程的第100天，终于完成了我的第一个应用程序，虽然简单但很有成就感！坚持就是胜利！",
        timeAgo = "2小时前",
        likes = 56,
        comments = 12,
        shares = 5
    ),
    Post(
        user = User("赵六"),
        content = "新买的相机到了，迫不及待地出去拍了几张照片，大家觉得怎么样？",
        timeAgo = "昨天",
        likes = 102,
        comments = 24,
        shares = 8
    ),
    Post(
        user = User("钱七"),
        content = "分享一道我最拿手的菜谱：红烧肉。准备材料：五花肉500g，生姜，大蒜，酱油，糖，八角...",
        timeAgo = "2天前",
        likes = 87,
        comments = 15,
        shares = 10
    )
) 